package com.tykhome.evernote.evernote2kindle.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Service;

import com.evernote.clients.NoteStoreClient;
import com.evernote.edam.error.EDAMNotFoundException;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.notestore.NoteFilter;
import com.evernote.edam.notestore.NoteList;
import com.evernote.edam.type.Data;
import com.evernote.edam.type.Note;
import com.evernote.edam.type.NoteSortOrder;
import com.evernote.edam.type.Notebook;
import com.evernote.edam.type.Resource;
import com.evernote.thrift.TException;
import com.tykhome.evernote.evernote2kindle.service.EvernoteNoteService;
import com.tykhome.evernote.evernote2kindle.util.NoteStoreUtil;

@Service
public class EvernoteNoteServiceImpl implements EvernoteNoteService {
	NoteStoreClient noteStore = NoteStoreUtil.getNoteStore();

	@Override
	public List<Note> listNotes() {
		List<Note> notes = new ArrayList<Note>();
		// First, get a list of all notebooks
		List<Notebook> notebooks = null;
		try {
			notebooks = noteStore.listNotebooks();
		} catch (EDAMUserException e) {
			e.printStackTrace();
		} catch (EDAMSystemException e) {
			e.printStackTrace();
		} catch (TException e) {
			e.printStackTrace();
		}

		for (Notebook notebook : notebooks) {
			// Next, search for the first 100 notes in this notebook, ordering
			// by creation date
			NoteFilter filter = new NoteFilter();
			filter.setNotebookGuid(notebook.getGuid());
			filter.setOrder(NoteSortOrder.CREATED.getValue());
			filter.setAscending(true);

			NoteList noteList = null;
			try {
				noteList = noteStore.findNotes(filter, 0, 100);
			} catch (EDAMUserException e) {
				e.printStackTrace();
			} catch (EDAMSystemException e) {
				e.printStackTrace();
			} catch (EDAMNotFoundException e) {
				e.printStackTrace();
			} catch (TException e) {
				e.printStackTrace();
			}
			notes.addAll(noteList.getNotes());
		}
		return notes;
	}

	@Override
	public List<Note> listNotes(Notebook notebook) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Map<String, String>> getResources(Note note) {
		List<Map<String, String>> res = new ArrayList<Map<String,String>>();
		Map<String, String> gm = null;
		List<Resource> resources = note.getResources();
		for(Resource resource : resources){
			gm = new HashMap<String, String>();
			Data data = resource.getData();
			if(null != data) gm.put(new String(Hex.encodeHex(data.getBodyHash())), resource.getGuid());
			res.add(gm);
		}
		return res;
	}

}
